package com.lz.ovuola.repository.mysql;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import com.lz.ovuola.util.constant.DataSourceConsts;
import com.lz.ovuola.util.exception.AppStartupException;
import com.lz.ovuola.util.threadlocal.DataSourceHolder;

@Component
public final class DynamicDataSource extends AbstractRoutingDataSource {

	@Autowired
	@Qualifier("primaryDS")
	private DataSource primaryDS;

	@Autowired
	@Qualifier("secondaryDS")
	private DataSource secondaryDS;

	private Map<Object, Object> dataSources;

	@PostConstruct
	public void init() {
		if ((!ObjectUtils.isEmpty(primaryDS))
				&& (!ObjectUtils.isEmpty(secondaryDS))) {
			dataSources = new HashMap<Object, Object>(2);
			dataSources.put(DataSourceConsts.PRIMARY_DS, primaryDS);
			dataSources.put(DataSourceConsts.SECONDARY_DS, secondaryDS);
		} else {
			throw new AppStartupException(
					"primaryDS or secondaryDS  is required,but is null");
		}
		setTargetDataSources(dataSources);
		setDefaultTargetDataSource(primaryDS);
	}

	@Override
	protected Object determineCurrentLookupKey() {
		return DataSourceHolder.getDataSource();
	}

	@Override
	public void setTargetDataSources(Map<Object, Object> targetDataSources) {
		super.setTargetDataSources(targetDataSources);
	}

	@Override
	public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
		super.setDefaultTargetDataSource(defaultTargetDataSource);
	}

	// public Map<Object, Object> getDataSources() {
	// return dataSources;
	// }

}
